<?php


namespace Wunder\Neo4j;

use Wunder\Neo4j\Connection\Connection;
use Wunder\Neo4j\Connection\ConnectionManager;
use Wunder\Neo4j\Exception\EormException;
use Wunder\Neo4j\Pool;
use Swoft\Bean\BeanFactory;

/**
 * Class Neo4j
 * @method static \GraphAware\Common\Result\Result|null run($query, $parameters = null, $tag = null, $connectionAlias = null)
 * @method static \GraphAware\Common\Result\Result runWrite($query, $parameters = null, $tag = null)
 * @method static \GraphAware\Common\Result\Result sendWriteQuery($query, $parameters = null, $tag = null)
 * @package Wunder\Neo4j
 */
class Neo4j
{
    /**
     * connection
     *
     * @param string $pool
     *
     * @return Connection
     * @throws EormException
     */
    public static function connection(string $pool = Pool::DEFAULT_POOL): Connection
    {
        try {
            /* @var ConnectionManager $conManager */
            $conManager = BeanFactory::getBean(ConnectionManager::class);

            /* @var Pool $eormPool */
            $eormPool  = bean($pool);
            $connection = $eormPool->getConnection();

            $connection->setRelease(true);
            $conManager->setConnection($connection);

        } catch (Exception $e) {
            throw new EormException(
                sprintf('Pool error is %s file=%s line=%d', $e->getMessage(), $e->getFile(), $e->getLine())
            );
        }

        return $connection;
    }

    /**
     * @param $name
     * @param $arguments
     * @return mixed
     * @throws ElasticsearchException
     */
    public static function __callStatic($name, $arguments)
    {
        /** @var Connection $instance */
        $instance = self::connection();
        return $instance->builder->adaptation($name,$arguments);
    }
}
